package com.YHVision.qiuzhike.service.impl;

import com.YHVision.qiuzhike.exception.BusinessException;
import com.YHVision.qiuzhike.model.entity.Company;
import com.YHVision.qiuzhike.service.CompanyService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.YHVision.qiuzhike.common.ErrorCode;
import com.YHVision.qiuzhike.mapper.CompanyFavourMapper;
import com.YHVision.qiuzhike.model.entity.CompanyFavour;
import com.YHVision.qiuzhike.model.entity.User;
import com.YHVision.qiuzhike.service.CompanyFavourService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 企业收藏服务实现
 *
 * @author <a href="">YHVision-小y</a>
 * @from <a href="todo">爱编程学习圈</a>
 */
@Service
@Slf4j
public class CompanyFavourServiceImpl extends ServiceImpl<CompanyFavourMapper, CompanyFavour> implements CompanyFavourService {

    @Resource
    private CompanyService companyService;
    /**
     * 用户对企业点赞
     *
     * @param companyId
     * @param loginUserId
     * @return
     */
    @Override
    public int doCompanyFavour(long companyId, User loginUserId) {
        //获取实体
        Company company = companyService.getById(companyId);
        if (company == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"数据不存在");
        }
        Long userId = loginUserId.getId();
        CompanyFavourService companyFavourService =(CompanyFavourService) AopContext.currentProxy();
        synchronized (String.valueOf(userId).intern()){
            return companyFavourService.doCompanyFavourInner(companyId,userId);
        }
    }

    /**
     *
     * 封装事务的实现方法
     * 用户点赞（内部实现）
     * @param companyId
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int doCompanyFavourInner(long companyId, Long userId) {
        //数据校验
        if (companyId <= 0  || userId <= 0) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        CompanyFavour companyFavour = new CompanyFavour();
        companyFavour.setCompanyId(companyId);
        companyFavour.setUserId(userId);
        QueryWrapper<CompanyFavour> companyFavourQueryWrapper = new QueryWrapper<>(companyFavour);
        CompanyFavour oldCompanyFavour = this.getOne(companyFavourQueryWrapper);
        boolean result;
        //用户已点赞
        if (oldCompanyFavour != null) {
            result = this.remove(companyFavourQueryWrapper);
            if (result){
                //点赞数-1
                result = companyService.update()
                        .eq("id",companyId)
                        .gt("favourNum",0)
                        .setSql("favourNum = favourNum - 1")
                        .update();
                return result ? -1 : 0;
            }
            else {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
            }
        }
        //用户未点赞
        else {
            result = this.save(companyFavour);
            if (result){
                //点赞数+1
                result = companyService.update()
                        .eq("id",companyId)
                        .setSql("favourNum = favourNum + 1")
                        .update();
                return result ? 1 : 0;
            }
            else {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
            }
        }
    }

    /**
     * 分页获取用户点赞列表
     *
     * @param page
     * @param queryWrapper
     * @param favourUserId
     * @return
     */
    @Override
    public Page<Company> listCompanyFavourByPage(IPage<Company> page, Wrapper<Company> queryWrapper, long favourUserId) {
        //数据校验
        if (favourUserId <= 0) {
            new Page<>();
        }
        return baseMapper.listFavourCompanyBypage(page,queryWrapper,favourUserId);
    }
}
